package com.zybzzz.workapp.fragment;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.DatePicker;
import android.app.DatePickerDialog.OnDateSetListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.zybzzz.workapp.MainActivity;
import com.zybzzz.workapp.R;
import com.zybzzz.workapp.entry.PlanMsg;
import com.zybzzz.workapp.entry.PlanMsgLab;
import com.zybzzz.workapp.entry.SinglePlanDateLab;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

public class PlanmsgFragment extends Fragment {

    private PlanMsg planMsg;
    private EditText planTitle;
    private EditText planRemark;
    private LinearLayout taskLinearLayout;
    private EditText taskNumEditText;
    private Button planCommitButton;


    private static final String ARG_PLAN_ID="plan_id";

    /**
     * 创建fragment实例的静态方法，这个方法会在创建该fragment的activity中被调用（PlanMsgActivity）
     * PlanMsgActivity在调用的时候会传入计划的id信息，并且这个id信息会传给fragment
     * 这样就能在fragment中通过id在（PlanMsgLab）的容器中找到对应的PlanMsg
     * @param: [planid]
     * @return: com.zybzzz.workapp.fragment.PlanmsgFragment
     * @author: ZhangYiBo
     * @date: 2020/10/15
     */
    public static PlanmsgFragment makeNewInstance(UUID planid){
        Bundle args=new Bundle();
        args.putSerializable(ARG_PLAN_ID,planid);

        PlanmsgFragment fragment=new PlanmsgFragment();
        fragment.setArguments(args);
        return fragment;
    }


    //多处需要添加合法性判断
    /**
     * 生命周期方法，在该fragment创建时进行的操作
     * @param: [savedInstanceState]
     * @return: void
     * @author: ZhangYiBo
     * @date: 2020/10/15
     */
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = getArguments();
        //无论如何都会包含ARG_PLAN_ID 不做有效性判断
        UUID planid=(UUID) getArguments().getSerializable(ARG_PLAN_ID);
        //仅对id在容器中是否存在进行判断
        if (PlanMsgLab.get(getActivity()).getPlanMsgById(planid)==null){
            //找不到新创建
            planMsg=new PlanMsg();
            planMsg.setId(planid);
        }else {
            //找的到直接取出来
            planMsg=PlanMsgLab.get(getActivity()).getPlanMsgById(planid);
        }

    }


    /**
     * 也是生命周期方法
     * @param: [inflater, container, savedInstanceState]
     * @return: android.view.View
     * @author: ZhangYiBo
     * @date: 2020/10/15
     */
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //加载原先设计好的fragment_planmsg到v中
        View v = inflater.inflate(R.layout.fragment_planmsg,container,false);

        //获取计划名称 添加监听
        planTitle = (EditText) v.findViewById(R.id.plantitle);
        //如果原先有信息的的就直接在文本输入框上显示信息，下同
        planTitle.setText(planMsg.getTitle());
        planTitle.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //从监听获取信息添加至实体类
//                planMsg.setTitle(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //获取计划的备注
        planRemark = (EditText) v.findViewById(R.id.planremark);
        planRemark.setText(planMsg.getRemark());
        planRemark.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //从监听获取信息添加至实体类
//                planMsg.setRemark(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //添加按钮的监听
        planCommitButton=(Button) v.findViewById(R.id.plancommitbtn);
        planCommitButton.setOnClickListener(new View.OnClickListener() {
            /**
             * 对提交按钮设置鼠标单击事件的监听，点击提交按钮完成信息的更新
             * 并且跳转到计划列表的显示界面，这个时候界面上的视图也会更新
             * @param: [v]
             * @return: void
             * @author: ZhangYiBo
             * @date: 2020/10/15
             */
            @Override
            public void onClick(View v) {
                //更新信息
                planMsg.setTitle(planTitle.getText().toString());
                planMsg.setRemark(planRemark.getText().toString());

                PlanMsgLab.get(getActivity()).addPlanMsg(PlanmsgFragment.this.planMsg);


                Intent intent = new Intent(PlanmsgFragment.this.getActivity(), MainActivity.class);
                startActivity(intent);
            }
        });

        //获取输入文本 设置失去焦点时候的属性
        //这个layout用于容纳动态生成的TaskItemFragment详细计划点（一个选择框和一个文本输入框）
        taskLinearLayout=(LinearLayout) v.findViewById(R.id.taskLinearLayoutContainer);
        //这个文本输入框输入的数字代表着下方生成几个详细计划点
        taskNumEditText=(EditText) v.findViewById(R.id.taskNumEditText);
        if (planMsg.getTaskTotalNum()!=null){
            //planMsg.getTaskTotalNum()不为空即代表着原先已经设置好详细计划点数目，加载即可
            taskNumEditText.setText(planMsg.getTaskTotalNum().toString());
            //加载详细计划点列表的函数，在后面定义
            generateTaskList(taskLinearLayout,planMsg.getTaskTotalNum());
        }
        taskNumEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            /**
             * 在数字输入框失去焦点的时候重新计算并生成相应数量的详细计划
             * @param: [v, hasFocus]
             * @return: void
             * @author: ZhangYiBo
             * @date: 2020/10/15
             */
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.d("onFocusChange","in focus change");
                if (!hasFocus){
                    Integer taskNum=Integer.parseInt(taskNumEditText.getEditableText().toString().trim());
                    generateTaskList(taskLinearLayout,taskNum);
//                    taskNumEditText.setText(taskNum.toString());

                }
            }
        });




        return v;
    }



    /**
     * 生成具体详细计划的函数
     * @param: [linearLayout, taskNum]
     * @return: void
     * @author: ZhangYiBo
     * @date: 2020/10/15
     */
    private void generateTaskList(LinearLayout linearLayout,Integer taskNum){
        Log.d("generateTaskList","in generateTaskList");
        if (taskNum>5){
            taskNum=5;
        }

        if (taskNum<=0){
            taskNum=0;
        }

        //更改原先文本框中的值
        taskNumEditText.setText(String.valueOf(taskNum));

        //直接在此处实现容器大小，不需要后面再去添加
        //原先容器为0，第一次加载
        //原先有容器大小遍历容器存储数据，将新的数据加载到容器的引用中
        if (planMsg.getTaskFinisheds().size()==0||planMsg.getTaskFinisheds().size()>taskNum){
            //直接创建固定长度的容器
            planMsg.setTaskFinisheds(Arrays.asList(new Boolean[taskNum]));
        }else {
            //取出原先容器中的信息，重新设置容器
            Boolean[] finished=new Boolean[taskNum];
            int count=0;
            for (Boolean existFinished : planMsg.getTaskFinisheds()) {
                finished[count]=existFinished;
                ++count;
            }
            planMsg.setTaskFinisheds(Arrays.asList(finished));
        }

        if (planMsg.getTaskItems().size()==0||planMsg.getTaskItems().size()>taskNum){
            planMsg.setTaskItems(Arrays.asList(new String[taskNum]));
        }else {
            String[] taskMsgs=new String[taskNum];
            int count=0;
            for (String existTaskItem : planMsg.getTaskItems()) {
                taskMsgs[count]=existTaskItem;
                ++count;
            }
            planMsg.setTaskItems(Arrays.asList(taskMsgs));
        }

        //继续设置容器
        if (planMsg.getTaskDates().size()==0||planMsg.getTaskDates().size()>taskNum){
            planMsg.setTaskDates(Arrays.asList(new String[taskNum]));
        }else {
            String[] taskDateMsgs=new String[taskNum];
            int count=0;
            for (String taskDateMsg : planMsg.getTaskDates()) {
                taskDateMsgs[count]=taskDateMsg;
                ++count;
            }
            planMsg.setTaskDates(Arrays.asList(taskDateMsgs));
        }
        if (planMsg.getTaskTimes().size()==0||planMsg.getTaskTimes().size()>taskNum){
            planMsg.setTaskTimes(Arrays.asList(new String[taskNum]));
        }else {
            String[] taskTimeMsgs=new String[taskNum];
            int count=0;
            for (String taskTimeMsg : planMsg.getTaskTimes()) {
                taskTimeMsgs[count]=taskTimeMsg;
                ++count;
            }
            planMsg.setTaskTimes(Arrays.asList(taskTimeMsgs));
        }

        //原先封装类中的总数可能为空 为空的话直接封装成0
        if (planMsg.getTaskTotalNum()==null){
            //尝试在子fragmentmanager中添加
            FragmentManager fm=this.getChildFragmentManager();
//        获取当前管理的fragment的数量
            //将数量记录在日志里是方便查看运行状态
            Log.e("generateTaskList","fragment num in list is "+fm.getFragments().size());
            Fragment fragment=fm.findFragmentById(R.id.taskLinearLayoutContainer);

            if (fragment==null){
                for (int num=0;num<taskNum;++num){
                    //将相应数量的fragment加载到taskLinearLayoutContainer容器中
                    fragment=TaskItemFragment.makeNewInstance(planMsg.getId(),planMsg,num);
                    fm.beginTransaction()
                            .add(R.id.taskLinearLayoutContainer,fragment)
                            .commit();
                }
            }
            //代表第一次形成 完成后直接返回
            planMsg.setTaskTotalNum(taskNum);
            return;
            //下面会包含这一段代码的大量重用
        }




        //后续不必考虑为空的情况
        if (taskNum==planMsg.getTaskTotalNum()){
            //直接生成  不需要后续操作
            //尝试在子fragmentmanager中添加
            FragmentManager fm=this.getChildFragmentManager();
//        获取当前管理的fragment的数量
            Log.e("generateTaskList","fragment num in list is(相等 仅生成) "+fm.getFragments().size());
            Fragment fragment=fm.findFragmentById(R.id.taskLinearLayoutContainer);

            if (fragment==null){
                for (int num=0;num<taskNum;++num){
                    fragment=TaskItemFragment.makeNewInstance(planMsg.getId(),planMsg,num);
                    fm.beginTransaction()
                            .add(R.id.taskLinearLayoutContainer,fragment)
                            .commit();
                }
            }
        }else if (taskNum>planMsg.getTaskTotalNum()){
            //用户需要的详细计划数目大于原有的数目，需要在manager中继续添加
            //尝试在子fragmentmanager中添加
            FragmentManager fm=this.getChildFragmentManager();
//        获取当前管理的fragment的数量
            Log.e("generateTaskList","fragment num in list is(添加) "+fm.getFragments().size());
            Fragment fragment=fm.findFragmentById(R.id.taskLinearLayoutContainer);

            if (fragment==null){
                for (int num=0;num<taskNum;++num){
                    fragment=TaskItemFragment.makeNewInstance(planMsg.getId(),planMsg,num);
                    fm.beginTransaction()
                            .add(R.id.taskLinearLayoutContainer,fragment)
                            .commit();
                }
            }else {
                for (int num=planMsg.getTaskTotalNum();num<taskNum;++num){
                    fragment=TaskItemFragment.makeNewInstance(planMsg.getId(),planMsg,num);
                    fm.beginTransaction()
                            .add(R.id.taskLinearLayoutContainer,fragment)
                            .commit();
                }
            }
        }else {
            //用户需要的详细计划数目小于原有的数目，清空fragmentmanager，然后重新添加新的
            //尝试在子fragmentmanager中添加
            FragmentManager fm=this.getChildFragmentManager();
//        获取当前管理的fragment的数量
            Log.e("generateTaskList","fragment num in list is(清空) "+fm.getFragments().size());
            Fragment fragment=fm.findFragmentById(R.id.taskLinearLayoutContainer);

            if (fragment==null){
                for (int num=0;num<taskNum;++num){
                    fragment=TaskItemFragment.makeNewInstance(planMsg.getId(),planMsg,num);
                    fm.beginTransaction()
                            .add(R.id.taskLinearLayoutContainer,fragment)
                            .commit();
                }
            }else {
                List<Fragment> fragments=fm.getFragments();
                FragmentTransaction transaction = fm.beginTransaction();
                for (Fragment f : fragments) {
                    transaction.remove(f);
                }
                transaction.commit();
                //前面已经处理好容器相关 后续不必要再考虑
//                planMsg.getTaskItems().clear();
//                planMsg.getTaskFinisheds().clear();

                for (int num=0;num<taskNum;++num){
                    fragment=TaskItemFragment.makeNewInstance(planMsg.getId(),planMsg,num);
                    fm.beginTransaction()
                            .add(R.id.taskLinearLayoutContainer,fragment)
                            .commit();
                }
            }
        }
        //操作完成之后更新当前的总计详细计划数目
        planMsg.setTaskTotalNum(taskNum);

//        //获取activity并添加fragment
////        FragmentManager fm=getActivity().getSupportFragmentManager();
//        //尝试在子fragmentmanager中添加
//        FragmentManager fm=this.getChildFragmentManager();
////        获取当前管理的fragment的数量
//        Log.e("generateTaskList","fragment num in list is "+fm.getFragments().size());
//        Fragment fragment=fm.findFragmentById(R.id.taskLinearLayoutContainer);
//
//        if (fragment==null){
//            for (int num=0;num<taskNum;++num){
//             fragment=TaskItemFragment.makeNewInstance(planMsg.getId(),num);
//             fm.beginTransaction()
//                     .add(R.id.taskLinearLayoutContainer,fragment)
//                     .commit();
//            }
//        }
//        //最后再改变原先存储的数字
//        planMsg.setTaskTotalNum(taskNum);
    }
}
